package
{
	import components.ECGDataLoader;
	import components.ECGSignal;

	import flash.display.Sprite;
	import flash.events.Event;
	/**
	 * @author perry
	 */
	public class ECGReader_DEMO extends Sprite
	{
		public static const NAME:String 			= "ECGReaderDemo";
		public static const COMPLETE:String			= NAME + "Complete";
		
		private const DEMO:Boolean					= true;
		
		private const SCALE:Number 			= 100;
		private const colorLine:Number		= 0xFFFFFF;
		private const strokeLine:Number		= 0.25;
		
		private var canvas:Sprite;
		private var loader:ECGDataLoader;
		private var plotData:Vector.<ECGSignal>;
		
		private var pos:int;
		private var totalTime:Number;
		private var halfStage:Number;
		
		public function ECGReader_DEMO()
		{
		}
		
		public function init():void
		{
			halfStage = stage.stageWidth;
			
			canvas = new Sprite();
			addChild( canvas );

			loader = new ECGDataLoader();
			loader.addEventListener( ECGDataLoader.COMPLETE, ECGDataCompleteHandler );
		}
		
		public function loadFile( path:String ):void
		{
			lock();
			canvas.graphics.clear();
			canvas.x = halfStage - canvas.width;
			canvas.graphics.lineStyle( strokeLine, colorLine );
			canvas.graphics.moveTo( 0, 0 );
			
			loader.init( path );
		}
		
		public function lock():void
		{
			this.removeEventListener(Event.ENTER_FRAME, loop );
		}
		
		public function unlock():void
		{
			this.addEventListener(Event.ENTER_FRAME, loop );
		}

		private function ECGDataCompleteHandler( e:Event ):void
		{
			plotData = loader.data;
			
			totalTime = plotData.length;
			
			pos = 0;
			
			dispatchEvent( new Event( COMPLETE ) );
			
			if( DEMO )
			{
				var i:uint;
				for( i = 0; i < plotData.length; i++ )
				{
					canvas.x = 0;
					if(plotData[i].t != 0 && plotData[i].mV != 0 )
					{
						canvas.graphics.lineTo(plotData[i].t * SCALE, plotData[i].mV * SCALE);
					}
				}
			}
			else
			{
				unlock();
			}
			
		}
		
		private function loop( e:Event ):void
		{
			canvas.graphics.lineTo(plotData[pos].t * SCALE, plotData[pos].mV * SCALE);
			
			if( pos + 1 >= totalTime )
			{
				lock();
			}

			canvas.x = halfStage - canvas.width;
			
			pos++;
		}

	}
}
